/***************/
const express = require("express");
const pool = require("../pool.js");
const router = express.Router();

let msg = [
  {
    code: 201,
    text: "成功",
  },
  {
    code: 202,
    text: "失败",
  },
  {
    code: 203,
    text: "手机号错误",
  },
];
//1.用户名与密码登陆接口
//测试地址：http://localhost:3000/v1/user/login
router.post("/login", (req, res) => {
  let u = req.body.uname;
  let p = req.body.upwd;
  let sql = "select uid from zm_user where uname=?&&upwd=?";
  pool.query(sql, [u, p], (err, r) => {
    if (err) throw err;
    r.length ? res.send("登陆成功") : res.send("账号密码错误");
  });
});
//2.手机号登录
router.post("/loginp", (req, res) => {
  let u = req.body.uphone;
  let sql = "select * from zm_user where uphone=?";
  pool.query(sql, [u], (err, r) => {
    if (err) throw err;
    if (r.length) {
      res.send(msg[0]);
    } else {
      res.send(msg[1]);
    }
  });
});
//3.手机号注册
router.post("/insert", (req, res) => {
  let u = `用户${req.body.uphone}`;
  let p = `123456789`;
  let ph = req.body.uphone;
  let exp = /^1[3-9]\d{9}$/;
  if (!exp.test(ph)) {
    res.send(msg[2]);
    return;
  } else {
    let sql = `insert into zm_user values(null,?,?,'1',?,"https://adm.hzsp.com/uploads/20221008/b362957f0f07702c9f360619283ccba7.jpg")`;
    pool.query(sql, [u, p, ph], (err, r) => {
      if (err) throw err;
      r.affectedRows ? res.send(msg[0]) : res.send(msg[1]);
    });
  }
});

module.exports = router;
